package com.onec.service.api.config;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

/**
 * dubbo 日志链路追踪
 *
 * @author onec
 */
@Activate(group = {CommonConstants.PROVIDER, CommonConstants.CONSUMER}, value = "tracing")
public class DubboTraceFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(DubboTraceFilter.class);
    /**
     * TraceId key
     */
    static final String TRACE_ID = "X-B3-TraceId";
    /**
     * SpanId key
     */
    static final String SPAN_ID = "X-B3-SpanId";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        // 获取dubbo上下文中的traceId
        String traceId = RpcContext.getContext().getAttachment(TRACE_ID);
        logger.info("TRACE_ID:{}:SPAN_ID:{}", MDC.get(TRACE_ID), MDC.get(SPAN_ID));
        if (StringUtils.isEmpty(traceId)) {
            // customer 设置traceId到dubbo的上下文
            RpcContext.getContext().setAttachment(TRACE_ID, MDC.get(TRACE_ID));
        } else {
            // provider 设置traceId到日志的上下文
            MDC.put(TRACE_ID, traceId);
        }
        logger.info(MDC.get(TRACE_ID));
        return invoker.invoke(invocation);
    }
}
